﻿using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace CodeFirst.Service
{
    using System;
    using System.Data.Entity;
    using System.Linq;

    public class CodeFirstContext : DbContext
    {
        public virtual DbSet<Student> Students { get; set; }
        public CodeFirstContext()
            : base("name=CodeFirstContext")
        {
            //设置自动迁移
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<CodeFirstContext, Migrations.Configuration>());
        }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            IEnumerable<IEntityMapper> entityMappers= GetMappers();
            foreach (IEntityMapper mapper in entityMappers)
            {
                mapper.RegistTo(modelBuilder.Configurations);
            }
        }

        /// <summary>
        /// 获取需要映射的实体列表
        /// </summary>
        /// <returns></returns>
        private static IEnumerable<IEntityMapper> GetMappers()
        {
            
            Type baseType = typeof(IEntityMapper);
            var paths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory+ "Plugins\\", "*.dll");
            List< Assembly > assemblies= paths.Select(s => Assembly.LoadFile(s)).ToList();

            var result = assemblies.SelectMany(assembly => assembly.GetTypes())
                   .Where(type => baseType.IsAssignableFrom(type) && type != baseType && !type.IsAbstract)
                   .Select(type => Activator.CreateInstance(type) as IEntityMapper);        
            return result;
        }

    }

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}